package com.wei.file.model;

import lombok.Data;
import org.springframework.util.ObjectUtils;

import java.io.File;

@Data
public class HttpRange {

    private long start;

    private long end;
    private HttpRange(long start,long end){
        this.start =start;
        this.end = Math.max(start, end);
    }


    public int getSuffixLength(){
        return (int) (end-start);
    }

    public static HttpRange parse(String range, File file){
        if(ObjectUtils.isEmpty(range)){
            return new HttpRange(0L,file.length());
        }
        if(range.indexOf("bytes=")==0){
            range = range.substring(6);
        }
        int dashIdx = range.indexOf('-');
        if (dashIdx > 0) {
            long firstPos = Long.parseLong(range, 0, dashIdx, 10);
            if (dashIdx < range.length() - 1) {
                long lastPos = Long.parseLong(range, dashIdx + 1, range.length(), 10);
                return new HttpRange(firstPos,Math.min(file.length(),lastPos) );
            }
            else {
                return new HttpRange(firstPos, file.length());
            }
        }
        else if (dashIdx == 0) {
            long suffixLength = Long.parseLong(range, 1, range.length(), 10);
            return new HttpRange(0L,Math.min(file.length(),suffixLength));
        }
        else {
            return new HttpRange(0L,file.length());
        }
    }
}
